package com.randi.common.core.domain.entity;

import com.baomidou.mybatisplus.annotation.*;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.randi.common.annotation.Excel;
import com.randi.common.config.AppConfig;
import com.randi.common.core.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Transient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @author ziye
 */
@EqualsAndHashCode(callSuper = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@Component
@TableName("sys_user")
@ApiModel(value = "SysUser", description = "系统用户对象")
public class SysUser extends BaseEntity {

    @TableId(value = "user_id", type = IdType.ASSIGN_ID)
    @JsonSerialize(using = ToStringSerializer.class)
    @ApiModelProperty(value = "用户ID")
    @Excel(name = "用户ID")
    private Long userId;

    @NotBlank(message = "用户账号不能为空")
    @TableField(value = "`user_name`")
    @ApiModelProperty(value = "用户账号")
    @Excel(name = "用户账号")
    private String userName;

    @NotBlank(message = "用户昵称不能为空")
    @TableField(value = "`nick_name`")
    @ApiModelProperty(value = "用户昵称")
    @Excel(name = "用户昵称")
    private String nickName;

    @TableField(value = "`email`")
    @ApiModelProperty(value = "用户邮箱")
    @Excel(name = "用户邮箱")
    private String email;

    @TableField(value = "`phone_number`")
    @ApiModelProperty(value = "手机号码")
    @Excel(name = "手机号码")
    private String phoneNumber;

    @TableField(value = "`sex`")
    @ApiModelProperty(value = "用户性别")
    @Excel(name = "用户性别", readConverterExp = "0=男,1=女,2=未知")
    private String sex;

    @TableField(value = "`avatar`")
    @ApiModelProperty(value = "头像地址")
    private String avatar;

    @JsonIgnore
    @TableField(value = "`password`")
    @ApiModelProperty(value = "密码")
    private String password;

    @TableField(exist = false)
    @ApiModelProperty(value = "角色组")
    private List<SysRole> roles;

    @Transient
    @ApiModelProperty(value = "超级用户ID")
    private static Long adminId;

    @Resource
    private void init(AppConfig.SystemConfig systemConfig) {
        adminId = systemConfig.getUserAdminId();
    }

    @Transient
    public String getKey() {
        return this.userId == null ? "" : this.userId.toString();
    }

    public boolean isAdmin() {
        return isAdmin(this.userId);
    }

    public static boolean isAdmin(Long userId) {
        return userId != null && userId.equals(adminId);
    }

}
